package com.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import com.fileutils.NumberUtils;
import com.jniutils.DataCollUtil;

import static com.fileutils.BaseConstant.*;

/**
 * 对日期操作的工具类
 *
 * @author wjl
 */
public class DateUtils {
    /**
     * 指定日期格式 yyyyMMddHHmmss
     */
    public static final String DATE_FORMAT_1 = "yyyyMMddHHmmss";

    /**
     * 指定日期格式 yyyy-MM-dd HH:mm:ss
     */
    public static final String DATE_FORMAT_2 = "yyyy-MM-dd HH:mm:ss";

    /**
     * 指定日期格式 yyyyMMddHHmmss
     */
    public static final String DATE_FORMAT_14 = "yyyyMMddHHmmss";

    /**
     * 指定日期格式 yyyy-MM-dd'T'HH:mm:ssZ
     */
    public static final String DATE_FORMAT_3 = "yyyy-MM-dd'T'HH:mm:ssZ";

    /**
     * 指定日期格式 yyyy-MM-dd
     */
    public static final String DATE_FORMAT_4 = "yyyy-MM-dd";

    /**
     * 指定日期格式 yyyy.M.d
     */
    public static final String DATE_FORMAT_5 = "yyyy.M.d";

    /**
     * 指定日期格式yyyy-MM-dd HH:mm
     */
    public static final String DATE_FORMAT_6 = "yyyy-MM-dd HH:mm";

    /**
     * 指定日期格式HH:mm
     */
    public static final String DATE_FORMAT_7 = "HH:mm";

    /**
     * 指定日期格式HH时mm分
     */
    public static final String DATE_FORMAT_12 = "HH时mm分";

    /**
     * 指定日期格式MM-dd HH:mm
     */
    public static final String DATE_FORMAT_8 = "MM-dd HH:mm";

    /**
     * 指定日期格式HH:MM:SS
     */
    public static final String DATE_FORMAT_9 = "HH:MM:SS";

    /**
     * 指定日期格式HH:mm
     */
    public static final String DATE_FORMAT_10 = "MM-dd";

    /**
     * 指定日期格式yy-MM-dd HH:mm
     */
    public static final String DATE_FORMAT_11 = "yy-MM-dd HH:mm";

    public static final String DATE_FORMAT_15 = "yyyyMMddHHmm";
    /**
     * 指定日期格式MM月dd日
     */
    public static final String DATE_FORMAT_13 = "MM月dd日";

    /**
     * 日期排序类型-升序
     */
    public final static int DATE_ORDER_ASC = 0;

    /**
     * 日期排序类型-降序
     */
    public final static int DATE_ORDER_DESC = 1;

    /**
     * 根据指定格式，获取现在时间
     */
    public static String getNowDateFormat(String format) {
        final Date currentTime = new Date();
        final SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(currentTime);
    }

    /**
     * 把String日期转成制定格式
     */
    @SuppressLint("SimpleDateFormat")
    public static String getDateFormat(String dateString, String sourceFormat, String targerFormat) {
        String s = "";
        if (!TextUtils.isEmpty(dateString)) {
            SimpleDateFormat sdf = new SimpleDateFormat(sourceFormat);
            try {
                Date date = sdf.parse(dateString);
                SimpleDateFormat sdfTarger = new SimpleDateFormat(targerFormat);
                s = sdfTarger.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return s;
    }

    /**
     * 把String日期转成制定格式
     */
    public static String getDateFormat(String dateString, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String s = "";
        try {
            Date date = sdf.parse(dateString);
            s = sdf.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 日期排序
     *
     * @param dates     日期列表
     * @param orderType 排序类型：DATE_ORDER_ASC，DATE_ORDER_DESC
     * @return 排序后的list
     * <p>
     * 用法 ArrayList<Date> dates = new ArrayList<Date>(); String dateStr
     * = "2011-10-25T00:00:00+08:00"; Date getDate =
     * getFormat("yyyy-MM-dd").parse(dateStr); dates.add(getDate);
     * <p>
     * orderDate(dates, DATE_ORDER_ASC);
     */
    public static ArrayList<Date> orderDate(ArrayList<Date> dates, int orderType) {
        final DateComparator comp = new DateComparator(orderType);
        Collections.sort(dates, comp);
        return dates;
    }

    private static class DateComparator implements Comparator<Date> {
        int orderType;

        public DateComparator(int orderType) {
            this.orderType = orderType;
        }

        @Override
        public int compare(Date d1, Date d2) {
            if (d1.getTime() > d2.getTime()) {
                if (orderType == DATE_ORDER_ASC) {
                    return 1;
                } else {
                    return -1;
                }
            } else {
                if (d1.getTime() == d2.getTime()) {
                    return 0;
                } else {
                    if (orderType == DATE_ORDER_DESC) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
            }
        }
    }

    /**
     * 时间校验
     *
     * @param sourceData
     * @param formatData
     * @return
     */
    public static boolean isValidDate(String sourceData, String formatData) {
        boolean convertSuccess = true;
        SimpleDateFormat format = new SimpleDateFormat(formatData);
        try {
            format.setLenient(false);
            format.parse(sourceData);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }

    /**
     * 格式化分钟
     *
     * @return
     */
    private static String minuteFormat(String dateValue) {
        if (dateValue.contains(".1克")) {
            return dateValue.replace(".1克", ":15");
        } else if (dateValue.contains(".1刻")) {
            return dateValue.replace(".1刻", ":15");
        } else if (dateValue.contains("点1刻")) {
            return dateValue.replace("点1刻", ":15");
        } else if (dateValue.contains("点1克")) {
            return dateValue.replace("点1克", ":15");
        } else if (dateValue.contains("点一刻")) {
            return dateValue.replace("点一刻", ":15");
        } else if (dateValue.contains("点一克")) {
            return dateValue.replace("点一克", ":15");
        } else if (dateValue.contains("点半")) {
            return dateValue.replace("点半", ":30");
        } else if (dateValue.contains(".半")) {
            return dateValue.replace(".半", ":30");
        }
        return dateValue;
    }

    /**
     * 时区判断
     *
     * @return
     */
    private static String timeZoneFormat(String dateValue) {
        if (dateValue.contains("凌晨")
                || dateValue.contains("早上")
                || dateValue.contains("早晨")
                || dateValue.contains("上午")
                || dateValue.contains("中午")) {
            return formatTo24(dateValue.replace("凌晨", "")
                    .replace("早上", "")
                    .replace("早晨", "")
                    .replace("上午", "")
                    .replace("中午", ""));
        } else if (dateValue.contains("晚上")
                || dateValue.contains("傍晚")) {
            String[] timeArr = dateValue.replace("傍晚", "")
                    .replace("晚上", "").split(":");
            return timeNight(timeArr[0]) + ":" + timeArr[1];
        } else if (dateValue.contains("下午")) {
            String[] timeArr = dateValue.replace("下午", "").split(":");
            return timePM(timeArr[0]) + ":" + timeArr[1];
        }
        if (dateValue.split(":")[0].length() == 1) {
            return "0" + dateValue;
        }
        return dateValue;
    }

    /**
     * 整点数据
     *
     * @param timeDate
     * @return
     */
    private static String oClockFormat(String timeDate) {
        if (timeDate.contains("时整") || timeDate.contains("时")) {
            return timeDate.replace("时整", ":00").replace("时", ":00");
        } else {
            String lastStr = timeDate.substring(timeDate.length() - 1);
            if (lastStr.equals(".")
                    || lastStr.equals("点")
                    || lastStr.equals(":")
                    || lastStr.equals("：")
                    || lastStr.equals("碘")) {
                return timeDate.substring(0, timeDate.length() - 1) + ":00";
            }
        }
        return timeDate;
    }

    /**
     * 时间标准化
     *
     * @param date
     */
    public static String dateFormat(int pattern1, String date,String formListStr){
        int mPattern=0,mPattern2=0;
        date=specificTime(date);
        if (date.equals("")){
            return date;
        }

        if(pattern1==0){
            mPattern=PATTERN_TIME_1;
            mPattern2=PATTERN_TIME_2;
        }else{
            mPattern=PATTERN_TIME_3;
            mPattern2=PATTERN_TIME_4;
        }

        String mTime1 = DataCollUtil.patternValue(mPattern, date);
        if (mTime1 != null && !mTime1.equals("")) {
            if(timeBeforeCheck(date,mTime1,formListStr)){
                return date;
            }else{
                return timeZoneFormat(NumberUtils.CharDateFormat(mTime1)
                        .replace(".", ":")
                        .replace("：", ":")
                        .replace(":", ":")
                        .replace("点", ":")
                        .replace("时", ":")
                        .replace("碘", ":")) + "|" + date.replace(mTime1, "");
            }
        } else {
            String mTime2 = DataCollUtil.patternValue(mPattern2, date);
            if(timeBeforeCheck(date,mTime1,formListStr)){
                return date;
            }else{
                if (mTime2 != null && !mTime2.equals("")) {
                    return timeZoneFormat(NumberUtils.CharDateFormat(oClockFormat(minuteFormat(mTime2))))
                            + "|" + date.replace(mTime2, "");
                }
            }
        }
        return date;
    }

    /**
     * 判断时间之前是否是数据项
     * @return
     */
    private static Boolean timeBeforeCheck(String sourceStr,String timeStr,String dataCheck){
        if(dataCheck.equals("")){
            return false;
        }
        int startIndex = sourceStr.indexOf(timeStr);
        if(startIndex>0){
            String[] dataArray = dataCheck.split("|");
            String headStr=sourceStr.substring(0,startIndex);
            for(String itemStr : dataArray){
                if(headStr.contains(itemStr)){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 特殊时间处理
     * @param timeStr
     * @return
     */
    private static String specificTime(String timeStr){
        switch (timeStr){
            case "起点": return "07:00";
            case "靶点": return "08:00";
            case "酒店": return "09:00";
        }
        return timeStr;
    }

    /**
     * 时间24小时制
     *
     * @param sourceData
     * @return
     */
    private static String formatTo24(String sourceData) {
        try {
            if (sourceData.substring(1, 2).equals(".") || sourceData.substring(1, 2).equals(":")) {
                sourceData = "0" + sourceData;
            }
        } catch (StringIndexOutOfBoundsException e) {
            return sourceData;
        }
        return sourceData;
    }

    /**
     * 下午时间标准化
     *
     * @param timeStr
     * @return
     */
    private static String timePM(String timeStr) {
        if (isNumeric(timeStr)) {
            int SourceTime = Integer.parseInt(timeStr);
            if (SourceTime > 0 && SourceTime < 12) {
                timeStr = "" + (SourceTime + 12);
            } else if (SourceTime == 12) {
                timeStr = "0";
            }
            return timeStr;
        } else {
            return "";
        }
    }

    /**
     * 晚上时间转换
     *
     * @param timeStr
     * @return
     */
    private static String timeNight(String timeStr) {
        if (isNumeric(timeStr)) {
            int SourceTime = Integer.parseInt(timeStr);
            if (SourceTime == 12 || SourceTime == 24) {
                timeStr = "0";
            } else if (SourceTime >= 4 && SourceTime <= 11) {
                timeStr = "" + (SourceTime + 12);
            }
            return timeStr;
        } else {
            return "";
        }
    }

    /**
     * 判断是否为数字
     *
     * @param str
     * @return
     */
    private static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 计算两个时间之间相隔天数
     *
     * @param startday 开始时间
     * @param endday   结束时间
     * @return
     */
    public static int getIntervalDays(Date startday, Date endday) {
        //确保startday在endday之前
        if (startday.after(endday)) {
            Date cal = startday;
            startday = endday;
            endday = cal;
        }
        //分别得到两个时间的毫秒数
        long sl = startday.getTime();
        long el = endday.getTime();

        long ei = el - sl;
        //根据毫秒数计算间隔天数
        return (int) (ei / (1000 * 60 * 60 * 24));
    }
}